package com.tv.cms.system.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.tv.cms.system.account.model.Account;
import com.tv.cms.system.admin.model.Admin;
import com.tv.cms.system.admin.service.AdminService;
import com.tv.cms.system.operator.model.Operator;
import com.tv.cms.system.role.model.Role;
import com.tv.cms.utils.InitPassword;
import com.tv.cms.utils.Md5encrypt;
import com.tv.cms.utils.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * TODO
 *
 * @author
 * @date
 **/
@RestController
@RequestMapping("admin")
public class AdminController {
    @Resource
    private AdminService service;
    /**
     * 用户信息
     *
     * @param admin
     * @return
     */
    @PostMapping("list")
    public Result<Page<Admin>> list(@RequestBody Admin admin){
        Admin a = service.getById(StpUtil.getLoginIdAsInt());
        MPJLambdaWrapper<Admin> wrapper = new MPJLambdaWrapper<Admin>()
                .selectAll(Admin.class)
                .selectAs(Role::getName , Admin :: getRoleName)
                .leftJoin(Role.class, Role :: getId, Admin :: getRoleId)
                .selectAs("t2.user_name", Admin :: getCreateName)
                .leftJoin("admin t2 ON (t2.id = t.create_by)")
                .selectAs("t3.user_name", Admin :: getUpdateName)
                .leftJoin("admin t3 ON (t3.id = t.update_by)")
                .selectAs("t4.name", Admin :: getOperatorName)
                .leftJoin("operator t4 ON (t4.id = t.operator_id)")
                .like(StringUtils.hasText(admin.getUserName()),"t.user_name",admin.getUserName())
                .eq(!Objects.isNull(admin.getRoleId()),"t1.id", admin.getRoleId())
                .eq(a.getRoleId() != 1, Admin :: getCreateBy,StpUtil.getLoginIdAsInt())
                .orderByDesc("t.status","t.create_time");
        Page<Admin> page = service.selectJoinListPage(new Page<>(admin.getPage(), admin.getLimit()), Admin.class, wrapper);
        Result<Page<Admin>> result = new Result<>();
        return  result.OKDATA(page);
    }

    /**
     * 添加用户
     * @param admin
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody Admin admin){
        if(!StringUtils.hasText(admin.getUserName())){
            return Result.FAILURE(400,"参数错误");
        }
        Admin one = service.getOne(new QueryWrapper<Admin>().eq("user_name", admin.getUserName()));
        if(one != null && admin.getId() == null){
            return Result.FAILURE("用户已存在");
        }
        if(one != null && admin.getId() != null && !Objects.equals(admin.getId(), one.getId())){
            return Result.FAILURE("用户已存在");
        }
        boolean b;
        if(admin.getId() != null){
            admin.setUpdateBy(StpUtil.getLoginIdAsInt());
            admin.setUpdateTime(new Date());
            b = service.updateById(admin);
        }else{
            admin.setCreateBy(StpUtil.getLoginIdAsInt());
            admin.setCreateTime(new Date());
            admin.setUpdateBy(StpUtil.getLoginIdAsInt());
            admin.setUpdateTime(new Date());
            admin.setStatus(1);
            admin.setPassword(InitPassword.getPassword());
            b = service.save(admin);
        }
        return b ? Result.OK() : Result.FAILURE();
    }

    /**
     * 更新用户状态
     * @param admin
     * @return
     */
    @PutMapping("status")
    public Result status(@RequestBody Admin admin){
        if(admin.getStatus() == null || admin.getId() == null){
            return Result.FAILURE(400,"参数错误");
        }
        Admin a = new Admin();
        a.setStatus(admin.getStatus());
        a.setId(admin.getId());
        boolean b = service.updateById(a);
        return b ? Result.OK() : Result.FAILURE();
    }

    /**
     * 校验密码
     * @param params
     * @return
     */
    @GetMapping("pwdValidate")
    public Result pwdValidate(@RequestParam Map<String,Object> params){
        Admin admin = service.getById(StpUtil.getLoginIdAsInt());
        String pwd = params.get("pwd").toString();
        if(admin.getPassword().equals(Md5encrypt.getMD5Str(pwd))){
            return Result.OK();
        }
        return Result.FAILURE(400,"原密码不正确");
    }

    /**
     * 更新密码
     * @param params
     * @return
     */
    @PostMapping("updatePassword")
    public Result updatePassword(@RequestBody Map<String,Object> params){
        Admin admin = new Admin();
        admin.setPassword(Md5encrypt.getMD5Str(params.get("pwd").toString()));
        admin.setId(StpUtil.getLoginIdAsInt());
        boolean b = service.updateById(admin);
        return b ? Result.OK() : Result.FAILURE();
    }

    /**
     * 初始化密码
     * @param admin
     * @return
     */
    @PostMapping("resetPassword")
    public Result resetPassword(@RequestBody Admin admin){
        admin.setPassword(Md5encrypt.getMD5Str("123456"));
        boolean b = service.updateById(admin);
        return b ? Result.OK() : Result.FAILURE();
    }
}
